const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
import m from "../models/EmailCode";
import mUser from "../models/User";
import _ from "lodash";
import { Request, Response } from "express";
import { NextFunction } from "express-serve-static-core";
import { notuser, pwderr } from "../config";

import utils from "../utils";

const moment = require("moment");

import { isEmail, isPhone, phoneCode, isDebug, emailCode } from "../config";

router.post(
  "/send",
  async (req: Request, res: Response, next: NextFunction) => {
    const { email, type } = req.body;
    // 目标
    const aim = email;

    let ret = undefined;

    if (!email) {
      res.json({
        code: "email_error",
        data: {},
        msg: "获取失败"
      });
      return;
    }

    // 邮箱不存在做拦截
    if (!mUser.hasEmail(aim)) {
      res.json({
        code: 200,
        data: {},
        msg: "获取成功"
      });
      return;
    }

    // code:String,
    // email:String,
    // createTime:String,
    // expireTime:String
    const code = utils.getCode();
    const createTime = moment();
    const expireTime = moment().add(emailCode.time, "s");
    ret = await m.create({
      email: aim,
      createTime: createTime.unix(),
      expireTime: expireTime.unix(),
      code
    });

    ret = await utils.sendEmail(aim, "发芽户外验证码", `您的验证码为${code}`);

    const data = {
      code,
      createTime: createTime.unix(),
      expireTime: expireTime.unix()
    };

    if (!isDebug) {
      delete data.code;
    }

    res.json({
      code: 200,
      data,
      msg: "获取成功"
    });
  }
);

module.exports = router;
